package main

import (
	"fmt"
	"game-server/config"
	"game-server/controller"
	"game-server/database"
	"game-server/handler"
	"game-server/manager"
	"game-server/middleware"
	"net/http"

	"log"
	pb "proto" // 这里需要替换成你的proto包路径

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"google.golang.org/grpc"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true // 在生产环境中应该检查来源
	},
}

type GameServer struct {
	crossClient pb.CrossServiceClient
	// 其他字段...
}

func main() {
	// 加载配置
	if err := config.LoadConfig("config.yaml"); err != nil {
		panic(fmt.Sprintf("Error loading config: %v", err))
	}

	// 初始化数据库
	dbConfig := config.GlobalConfig.Database
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=%v&loc=%s",
		dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port,
		dbConfig.DBName, dbConfig.Charset, dbConfig.ParseTime, dbConfig.Loc)

	if err := database.InitDB(dsn); err != nil {
		panic(fmt.Sprintf("Error connecting to database: %v", err))
	}

	// 初始化连接管理器
	clientManager := manager.NewClientManager()
	go clientManager.Run()

	// 连接到cross-server
	conn, err := grpc.Dial(config.GlobalConfig.CrossServer.Address, grpc.WithInsecure())
	if err != nil {
		log.Fatalf("Failed to connect to cross server: %v", err)
	}
	defer conn.Close()

	// 创建cross-server的客户端
	crossClient := pb.NewCrossServiceClient(conn)

	// 连接到battle-server
	battleConn, err := grpc.Dial("localhost:50052", grpc.WithInsecure())
	if err != nil {
		log.Fatalf("Failed to connect to battle server: %v", err)
	}
	defer battleConn.Close()
	battleClient := pb.NewBattleServiceClient(battleConn)

	// 初始化controllers
	battleController := controller.NewBattleController(battleClient)

	// 初始化game server
	gameServer := &GameServer{
		crossClient: crossClient,
	}

	r := gin.Default()

	// 添加CORS中间件
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	// WebSocket 连接处理
	r.GET("/ws", gameServer.handleWebSocket)

	// 英雄相关路由
	heroController := controller.NewHeroController()
	r.GET("/heroes", middleware.AuthMiddleware(), heroController.GetAllHeroes)

	// 布阵相关路由
	formationController := controller.NewFormationController()
	r.GET("/heroes/owned", middleware.AuthMiddleware(), formationController.GetOwnedHeroes)
	r.GET("/formation", middleware.AuthMiddleware(), formationController.GetFormation)
	r.POST("/formation", middleware.AuthMiddleware(), formationController.SaveFormation)

	// 调用rpc
	r.GET("/match", middleware.AuthMiddleware(), gameServer.handlerRpcMatch)

	// 添加battle相关路由
	r.GET("/battle/result/:battleId", middleware.AuthMiddleware(), battleController.GetBattleResult)

	// 启动服务器
	addr := fmt.Sprintf(":%d", config.GlobalConfig.Server.Port)
	fmt.Printf("Game server starting on %s\n", addr)
	r.Run(addr)
}

func (gs *GameServer) handleWebSocket(c *gin.Context) {
	wsHandler := handler.NewWebSocketHandler(gs.crossClient)
	wsHandler.HandleWebSocket(c.Writer, c.Request)
}

func (gs *GameServer) handlerRpcMatch(c *gin.Context) {
	matchController := controller.NewMatchController(gs.crossClient)
	matchController.TestRpcMatch(c)
}
